package com.ujn.demo.controller;

import com.alibaba.fastjson.JSON;
import com.ujn.demo.model.TbOsdModel;
import com.ujn.demo.service.OsdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

@Api(tags="osd设备管理")
@RestController
public class OsdController {

    private static final Logger logger = LoggerFactory.getLogger(OsdController.class);

    @Autowired
    private OsdService osdService;

    /**
     * @description 读取excel（excel在resources下）
     * @author sunjx
     * @date 2020/9/1 14:14
     * @param file
     * @return java.util.Map<java.lang.String,com.ujn.demo.model.TbOsdModel>
     **/
    @ApiOperation(value = "批量导入设备（osd）excel")
    @PostMapping("/osd/import")
    public Map<String, TbOsdModel> importOsd(@RequestParam("file") MultipartFile file){
        Instant start = Instant.now();
        Map<String, TbOsdModel> map = osdService.importExcel(file);
        Instant end = Instant.now();
        logger.info("执行importOsd方法：结束, map:{}, 导入excel总耗时：{}秒", JSON.toJSON(map), Duration.between(start, end).getSeconds());
        return map;
    }

    /**
     * @description 导出excel（excel在resources下）
     * @author sunjx
     * @date 2020/9/1 14:14
     * @param request
     * @param response
     * @return java.util.Map<java.lang.String,com.ujn.demo.model.TbOsdModel>
     **/
    @ApiOperation(value = "批量导出设备（osd）excel")
    @GetMapping("/osd/export")
    public void exportOsd(HttpServletRequest request, HttpServletResponse response){
        Instant start = Instant.now();
        HSSFWorkbook sheets = osdService.exportExcel();
        //日期转字符串
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
        String str = format.format(date);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try (OutputStream os = response.getOutputStream();){
            if (request.getHeader("User-Agent").toLowerCase().contains("firefox")) {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode("设备列表" + str  +".xls", "utf-8"));
            }else {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("设备列表" +  str +".xls", "utf-8"));
            }
            sheets.write(os);
            os.flush();
            os.close();
            Instant end = Instant.now();
            logger.info("执行exportOsd方法：结束, 导出excel总耗时：{}秒", Duration.between(start, end).getSeconds());
        } catch (Exception e) {
            logger.error("exportExcel, 错误信息：{}", e);
        }
    }
}